//
//  CommentViewController.m
//  tcpoctest
//
//  Created by apple on 13-4-26.
//  Copyright (c) 2013年 gump. All rights reserved.
//

#import "CommentViewController.h"
#import "SZTextView.h"
#import "FTWButton.h"
#import "FirCirVoiceTipsView.h"
#import "recordManager.h"
#import "SpeexCodec.h"
#import "FirCirCommentDataSource.h"

#import "sendFirCirComment.h"
#import "taskDataSource.h"

#import <AVFoundation/AVFoundation.h>

@interface CommentViewController ()
{
    SZTextView          *inputTextView;
    UIScrollView        *scroll;
    UIPageControl       *pageController;
    
    FTWButton           *vpvplaybtn;
    FTWButton           *vpvdelbtn;
    FTWButton           *voiceBtn;
    FTWButton           *vpvsendbtn;
    UIView              *voiceInputView;
    UIImageView         *voiceInputIcon;
    
    FirCirVoiceTipsView       *voiceTipsView;
    int                 iCommentState;
    NSTimer             *voiceRecordTimer;
    int                 iSubmitTime;
    bool                brecord;//是否录音
    int                 istindex;
    
    AVAudioPlayer       *player;
}
@end

@implementation CommentViewController

-(void)initUI
{
    self.view.backgroundColor = VIEW_BG_COLOR;
    
    [self createTitle];
    self.mtitle.text = @"评论";
    
    UIBarButtonItem *backItem = [self createBarBackButtonItemWithTitle:@"返回"
                                                                target:self action:@selector(backButtonPressed)];
    self.navItem.leftBarButtonItem = backItem;
    
    UIBarButtonItem *nextItem = [self createBarButtonItemWithTitle:@"发布"
                                                            target:self
                                                            action:@selector(sendNewStatus)];
    self.navItem.rightBarButtonItem = nextItem;
    
    scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 44, WINDOW_WIDTH, WINDOW_HIGTH - 44)];
    scroll.contentSize=CGSizeMake(self.view.bounds.size.width*2, scroll.bounds.size.height);
    scroll.showsHorizontalScrollIndicator=NO; 
    scroll.showsVerticalScrollIndicator=NO;
    scroll.pagingEnabled=YES;
    scroll.delegate = self;
    [self.view addSubview:scroll];
    
    pageController = [[UIPageControl alloc] initWithFrame:CGRectMake(0, WINDOW_HIGTH - 80, WINDOW_WIDTH, 44)];
    pageController.numberOfPages=2;
    pageController.currentPage=0;
    pageController.userInteractionEnabled=NO;
    [self.view addSubview:pageController];
    
    inputTextView = [[SZTextView alloc]initWithFrame:CGRectMake(0, 0, 320, 120)];
    inputTextView.placeholder = @"说点什么吧";
    inputTextView.font = [UIFont fontWithName:@"HelveticaNeue-Light" size:18.0];
    inputTextView.userInteractionEnabled = YES;
    [scroll addSubview:inputTextView];
    
    [inputTextView becomeFirstResponder];
    
    voiceInputView = [[UIView alloc]initWithFrame:CGRectMake(WINDOW_WIDTH, 40, 320, 216)];
    voiceInputView.backgroundColor = [UIColor colorWithRed:243.0/255.0 green:243.0/255.0 blue:243.0/255.0 alpha:1];
    
    voiceInputIcon = [[UIImageView alloc]initWithFrame:CGRectMake(112, 27, 96, 96)];
    voiceInputIcon.image = [UIImage imageNamed:@"bg_Voice_Input.png"];
    [voiceInputView addSubview:voiceInputIcon];
    [scroll addSubview:voiceInputView];
    
    voiceBtn = [[FTWButton alloc] init];
    voiceBtn.frame = CGRectMake(7, 150, 306, 44);
    [voiceBtn addBlueStyleForState:UIControlStateNormal];
    [voiceBtn setText:@"按住录音" forControlState:UIControlStateNormal];
    [voiceBtn setFont:[UIFont systemFontOfSize:18]];
    [voiceBtn addTarget:self action:@selector(voiceBtnClipUp) forControlEvents:UIControlEventTouchUpInside];
    [voiceBtn addTarget:self action:@selector(voiceBtnClip) forControlEvents:UIControlEventTouchDown];
    [voiceInputView addSubview:voiceBtn];
    
    vpvplaybtn = [[FTWButton alloc] initWithFrame:CGRectMake(44, 150, 70, 44)];
    [vpvplaybtn addBlueStyleForState:UIControlStateNormal];
    [vpvplaybtn setText:@"播放" forControlState:UIControlStateNormal];
    [vpvplaybtn addTarget:self action:@selector(playRedio) forControlEvents:UIControlEventTouchUpInside];
    [vpvplaybtn setHidden:YES];
    [voiceInputView addSubview:vpvplaybtn];
    
    vpvsendbtn = [[FTWButton alloc] initWithFrame:CGRectMake(124, 150, 70, 44)];
    [vpvsendbtn addBlueStyleForState:UIControlStateNormal];
    [vpvsendbtn setText:@"发送" forControlState:UIControlStateNormal];
    [vpvsendbtn addTarget:self action:@selector(sendRedio) forControlEvents:UIControlEventTouchUpInside];
    [vpvsendbtn setHidden:YES];
    [voiceInputView addSubview:vpvsendbtn];
    
    vpvdelbtn = [[FTWButton alloc] initWithFrame:CGRectMake(204, 150, 70, 44)];
    [vpvdelbtn addDeleteStyleForState:UIControlStateNormal];
    [vpvdelbtn setText:@"删除" forControlState:UIControlStateNormal];
    [vpvdelbtn addTarget:self action:@selector(delRedio) forControlEvents:UIControlEventTouchUpInside];
    [vpvdelbtn setHidden:YES];
    [voiceInputView addSubview:vpvdelbtn];
    
    voiceTipsView = nil;
}

#pragma mark -private fun-
-(void)backButtonPressed
{
    [[ViewManager sharedViewManager] backView:self];
}

-(void)sendNewStatus
{
    if ([self CheckInput]) {
        iCommentState = CS_SUBMIT;
        
        [[ViewManager sharedViewManager] showProgressHUDWithStatus:@"正在发布" withView:self.view];
        
        if (istindex == FCG_ONE_TEXT) {
            if ([inputTextView isFirstResponder]) {
                [inputTextView resignFirstResponder];
            }
            
            [[DataControl shareControl].fccommentDS SetCSInfoIndex:istindex
                                                       withContent:inputTextView.text];
        }
        else if(istindex == FCG_ONE_SOUND)
        {
            [[DataControl shareControl].fccommentDS SetCSInfoIndex:istindex
                                                       withContent:[[recordManager shareControl].recordedFile path]];

        }
        
        [[netManager sharedNetManager].sendFCComment SendFCComment:
         [[DataControl shareControl].fccommentDS SendCommentInfo]];
    }
}

- (void)levelTimerCallback:(NSTimer *)timer {
	double power = [[recordManager shareControl] updateRecordPower];
    
    if (power == 0) {
        return;
    }
    
	int index = 0;
	if (power <= 0.1) {
		index = 1;
	}else if (power > 0.1 && power <= 0.2){
		index = 2;
	}else if (power > 0.2 && power <= 0.3){
		index = 3;
	}else if (power > 0.3 && power <= 0.4){
		index = 4;
	}else if (power > 0.4 && power <= 0.45) {
		index = 5;
	}else if (power > 0.45 && power <= 0.5){
		index = 6;
	}
	else if (power > 0.5){
		index = 7;
	}
	if (voiceTipsView) {
		[voiceTipsView updatePttSoundVolumImage:index];
	}
}

-(bool)CheckInput
{
    bool binput = false;
    
    if (istindex == FCG_ONE_SOUND) {
        if (brecord) {
            binput = true;
        }
        else
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                            message:@"不能木有声音哦"
                                                           delegate:self
                                                  cancelButtonTitle:@"确认"
                                                  otherButtonTitles:nil];
            [alert show];
        }
    }
    else if(istindex == FCG_ONE_TEXT)
    {
        if (![inputTextView.text isEqualToString:@""]) {
            binput = true;
        }
        else
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                            message:@"评论不能为空哦"
                                                           delegate:self
                                                  cancelButtonTitle:@"确认"
                                                  otherButtonTitles:nil];
            [alert show];
        }
    }
    
    return binput;
}

-(void)voiceBtnClip
{
    AVAudioSession *session = [AVAudioSession sharedInstance];
    NSError *sessionError;
    [session setCategory:AVAudioSessionCategoryPlayback error:&sessionError];
    
    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
    
    if(session == nil)
    {
        AS_LOG(@"Error creating session: %@", [sessionError description]);
    }
    else
        [session setActive:YES error:nil];
    
    if (nil == voiceTipsView) {
		voiceTipsView = [[FirCirVoiceTipsView alloc] initWithFrame:CGRectMake(70, -40, 184, 184)];
	}
	[voiceTipsView showPttStartImageBySuperView:voiceInputView];
    [voiceInputIcon setHidden:YES];
    [[recordManager shareControl] startRecord];
    iCommentState = CS_SOUND;
    voiceRecordTimer = [NSTimer scheduledTimerWithTimeInterval:0.03 target: self selector: @selector(levelTimerCallback:) userInfo: nil repeats: YES];
    iSubmitTime = 0;
}

-(void)voiceBtnClipUp
{
    iCommentState  = CS_NULL;
    if (iSubmitTime < 10) {
        [[recordManager shareControl] stopRecord];
        [voiceRecordTimer invalidate];
        [voiceTipsView showPttFailImage];
        [self performSelector:@selector(dismissVoiceTipsView) withObject:nil afterDelay:1.2];
    }
    else
    {
        [[recordManager shareControl] stopRecord];
        [voiceRecordTimer invalidate];
        iSubmitTime = 0;
        [self dismissVoiceTipsView];
        
        [voiceBtn setHidden:YES];
        [vpvdelbtn setHidden:NO];
        [vpvplaybtn setHidden:NO];
        [vpvsendbtn setHidden:NO];
        brecord = true;
    }
    
    iSubmitTime = 0;
}

-(void)dismissVoiceTipsView
{
    [voiceTipsView dismissTips];
    [voiceInputIcon setHidden:NO];
}

-(void)playRedio
{
    if (player != nil && [player isPlaying]) {
        return;
    }
    
    AVAudioSession *session = [AVAudioSession sharedInstance];
    NSError *sessionError;
    [session setCategory:AVAudioSessionCategoryPlayback error:&sessionError];
    
    if(session == nil)
    {
        AS_LOG(@"Error creating session: %@", [sessionError description]);
    }
    else
        [session setActive:YES error:nil];
    NSError *playerError;
    NSData *SpeexData = [NSData dataWithContentsOfFile:[[recordManager shareControl].recordedFile path]];
    NSData *NewPCMData = DecodeSpeexToWAVE(SpeexData);
    player = [[AVAudioPlayer alloc] initWithData:NewPCMData error:&playerError];
    AS_LOG(@"voice length is %f",player.duration);
    [player prepareToPlay];
    [player play];
}

-(void)delRedio
{
    [[FileManager shareControl] deleteFile:[[recordManager shareControl].recordedFile path]];
    [vpvplaybtn setHidden:YES];
    [vpvdelbtn setHidden:YES];
    [vpvsendbtn setHidden:YES];
    [voiceBtn setHidden:NO];
    
    brecord = false;
}

-(void)sendRedio
{
    if ([self CheckInput]) {
        iCommentState = CS_SUBMIT;
        
        [[ViewManager sharedViewManager] showProgressHUDWithStatus:@"正在发布" withView:self.view];
        
        if (istindex == FCG_ONE_TEXT) {
            if ([inputTextView isFirstResponder]) {
                [inputTextView resignFirstResponder];
            }
            
            [[DataControl shareControl].fccommentDS SetCSInfoIndex:istindex
                                                       withContent:inputTextView.text];
        }
        else if(istindex == FCG_ONE_SOUND)
        {
            [[DataControl shareControl].fccommentDS SetCSInfoIndex:istindex
                                                       withContent:[[recordManager shareControl].recordedFile path]];
            
        }
        
        [[netManager sharedNetManager].sendFCComment SendFCComment:
         [[DataControl shareControl].fccommentDS SendCommentInfo]];
    }
}

-(void)UICustomTick
{
    switch (iCommentState) {
        case CS_SOUND:
        {
            iSubmitTime++;
        }
            break;
        case CS_SUBMIT:
        {
            if (iSubmitTime < 200) {
                iSubmitTime++;
            }
            else
            {
                iCommentState = CS_NULL;
                iSubmitTime = 0;
                
                [[ViewManager sharedViewManager] ChangeHUDShowFail:@"发布超时"];
                [self performSelector:@selector(showinputkey) withObject:nil afterDelay:1];
            }
        }
            break;
        default:
            break;
    }
}

-(void)showinputkey
{
    if (![inputTextView isFirstResponder]) {
        [inputTextView becomeFirstResponder];
    }
}

-(void)viewWillShow
{
    if (![inputTextView isFirstResponder]) {
        [inputTextView becomeFirstResponder];
    }
    inputTextView.text = @"";
    
    [vpvplaybtn setHidden:YES];
    [vpvdelbtn setHidden:YES];
    [vpvsendbtn setHidden:YES];
    [voiceBtn setHidden:NO];
    [voiceInputIcon setHidden:NO];
    
    iCommentState = CS_NULL;
    iSubmitTime = 0;
    brecord = false;
    istindex = FCG_ONE_TEXT;
}

-(void)viewWillHide
{
    if (brecord) {
        [[FileManager shareControl] deleteFile:[[recordManager shareControl].recordedFile path]];
        [vpvplaybtn setHidden:YES];
        [vpvdelbtn setHidden:YES];
        [vpvsendbtn setHidden:YES];
        [voiceBtn setHidden:NO];
        
        brecord = false;
    }
}

-(void)NewsSendSuccess
{
    if (iCommentState == CS_SUBMIT) {
        iCommentState = CS_NULL;
        iSubmitTime = 0;
        
        [[ViewManager sharedViewManager] ChangeHUDShowSuccess:@"发布成功！"];
        [self performSelector:@selector(backButtonPressed) withObject:nil afterDelay:1];
        
        [[DataControl shareControl].taskDS CompleteTaskByID:TI_F_COMMENT
                                           withIsDirectShow:true];
    }
}

-(void)NewsSendFail
{
    if (iCommentState == CS_SUBMIT) {
        iCommentState = CS_NULL;
        iSubmitTime = 0;
        
        [[ViewManager sharedViewManager] ChangeHUDShowFail:@"发布太频繁，请稍后发布"];
        [self performSelector:@selector(showinputkey) withObject:nil afterDelay:1];
    }
    
}

#pragma mark -scrollview delegate-
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    if(scrollView==scroll){
        CGPoint offset = scrollView.contentOffset;
        pageController.currentPage = offset.x / (self.view.bounds.size.width); 
        [scroll setContentOffset:CGPointMake(self.view.bounds.size.width * (pageController.currentPage),
                                             scroll.contentOffset.y) animated:YES];
        if (pageController.currentPage == 1) {
            if ([inputTextView isFirstResponder]) {
                [inputTextView resignFirstResponder];
            }
            
            istindex = FCG_ONE_SOUND;
        }
        else if (pageController.currentPage == 0)
        {
            if (![inputTextView isFirstResponder]) {
                [inputTextView becomeFirstResponder];
            }
            
            istindex = FCG_ONE_TEXT;
        }
    }
}

@end
